package com.ruizhong.integratedmediawithoutc.util;

import com.ruizhong.integratedmediawithoutc.controller.SystemController;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.io.IOException;
import java.nio.file.*;
import java.util.HashSet;
import java.util.function.Consumer;
import java.util.stream.Stream;

import static java.nio.file.StandardWatchEventKinds.*;

@Component
public class FolderActivityMonitor {

    public static HashSet<String> fileNamesSet = new HashSet<>();
    private volatile boolean running = true;  // 添加运行状态标志
    private WatchService watchService;  // 将watchService提升为成员变量
    private Thread monitorFiles;

    @PostConstruct
    public void monitor() {
        monitorFiles = new Thread(() -> {
            getFiles();
            System.out.println("初始文件列表: " + fileNamesSet);

            // 设置要监听的文件夹路径
            Path folderPath = Paths.get(SystemController.share_dir);

            try {
                watchService = FileSystems.getDefault().newWatchService();
                // 注册监听事件（创建、修改、删除）
                folderPath.register(watchService, ENTRY_CREATE, ENTRY_MODIFY, ENTRY_DELETE);

                System.out.println("开始监听文件夹: " + folderPath);
                System.out.println("监听事件: 文件创建、修改、删除");

                while (running) {  // 使用running标志控制循环
                    WatchKey key;
                    try {
                        key = watchService.take();  // 可中断的等待
                    } catch (InterruptedException e) {
                        System.out.println("监听线程被中断");
                        break;
                    }

                    for (WatchEvent<?> event : key.pollEvents()) {
                        // 跳过OVERFLOW事件
                        WatchEvent.Kind<?> kind = event.kind();
                        if (kind == OVERFLOW) {
                            continue;
                        }

                        // 获取文件名
                        String fileName = event.context().toString();

                        if (kind == ENTRY_CREATE) {
                            fileNamesSet.add(fileName);
                        } else if (kind == ENTRY_DELETE) {
                            fileNamesSet.remove(fileName);
                        }
                        System.out.println("当前文件列表: " + fileNamesSet);
                    }

                    if (!key.reset()) {
                        System.out.println("WatchKey已失效");
                        break;
                    }
                }
            } catch (Exception e) {
                if (running) {  // 如果不是因为关闭导致的异常
                    e.printStackTrace();
                }
            } finally {
                closeResources();  // 确保资源被关闭
            }
        });
        monitorFiles.start();
    }

    @PreDestroy
    public void closeMonitoring() {
        System.out.println("正在停止文件夹监听...");
        running = false;  // 设置标志位

        if (monitorFiles != null) {
            monitorFiles.interrupt();  // 中断线程
            try {
                monitorFiles.join(1000);  // 等待线程结束
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }

        closeResources();  // 关闭资源
        System.out.println("文件夹监听已停止");
    }

    private void closeResources() {
        try {
            if (watchService != null) {
                watchService.close();
            }
        } catch (IOException e) {
            System.err.println("关闭WatchService时出错: " + e.getMessage());
        }
    }

    private void getFiles() {
        String folderPath = SystemController.share_dir;
        try (Stream<Path> paths = Files.walk(Paths.get(folderPath))) {
            paths.filter(Files::isRegularFile)  // 只获取文件，不包括目录
                    .forEach(path -> fileNamesSet.add(path.getFileName().toString()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}